const fs = require('fs');
const path = require('path');
const sass = require('sass');

// 递归查找所有 SCSS 文件
function findScssFiles(dir) {
  const files = [];
  const items = fs.readdirSync(dir);
  
  for (const item of items) {
    const fullPath = path.join(dir, item);
    const stat = fs.statSync(fullPath);
    
    if (stat.isDirectory()) {
      files.push(...findScssFiles(fullPath));
    } else if (item.endsWith('.scss') || item.endsWith('.sass')) {
      files.push(fullPath);
    }
  }
  
  return files;
}

// 转换单个 SCSS 文件为 CSS
function convertScssToCss(scssPath) {
  try {
    console.log(`Converting: ${scssPath}`);
    
    // 读取 SCSS 文件
    const scssContent = fs.readFileSync(scssPath, 'utf8');
    
    // 编译 SCSS 为 CSS
    const result = sass.compile(scssPath, {
      style: 'expanded',
      sourceMap: false
    });
    
    // 生成 CSS 文件路径
    const cssPath = scssPath.replace(/\.(scss|sass)$/, '.css');
    
    // 写入 CSS 文件
    fs.writeFileSync(cssPath, result.css);
    
    console.log(`✓ Created: ${cssPath}`);
    
    // 更新引用该 SCSS 文件的 JS 文件
    updateJsImports(scssPath, cssPath);
    
  } catch (error) {
    console.error(`✗ Error converting ${scssPath}:`, error.message);
  }
}

// 更新 JS 文件中的导入
function updateJsImports(scssPath, cssPath) {
  const jsDir = path.dirname(scssPath);
  const jsFiles = fs.readdirSync(jsDir).filter(f => f.endsWith('.js'));
  
  for (const jsFile of jsFiles) {
    const jsPath = path.join(jsDir, jsFile);
    let jsContent = fs.readFileSync(jsPath, 'utf8');
    
    // 替换 SCSS 导入为 CSS 导入
    const scssFileName = path.basename(scssPath);
    const cssFileName = path.basename(cssPath);
    
    if (jsContent.includes(scssFileName)) {
      jsContent = jsContent.replace(
        new RegExp(scssFileName.replace(/\./g, '\\.'), 'g'),
        cssFileName
      );
      fs.writeFileSync(jsPath, jsContent);
      console.log(`  Updated imports in: ${jsPath}`);
    }
  }
}

// 主函数
function main() {
  console.log('Starting SCSS to CSS conversion...\n');
  
  const scssFiles = findScssFiles('./client');
  console.log(`Found ${scssFiles.length} SCSS files to convert.\n`);
  
  for (const scssFile of scssFiles) {
    convertScssToCss(scssFile);
  }
  
  console.log('\nConversion completed!');
  console.log('Note: You may need to manually update some import statements.');
}

main(); 